package cn.com.jenson.util;

import cn.com.jenson.dao.user.vo.UserVo;
import cn.com.jenson.entity.user.Role;
import cn.com.jenson.entity.user.User;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ObjectsUtil {
    public static <V> @NotNull V copyProperties(Object e, @NotNull Class<V> clazz, String... ignoreProperties) throws InstantiationException, IllegalAccessException {
        V v = clazz.newInstance();
        Field[] declaredFields = clazz.getDeclaredFields();
        System.out.println(Arrays.toString(declaredFields));;
        BeanUtils.copyProperties(e, v,ignoreProperties);
        return v;
    }

    public static <V> @NotNull List<V> copyProperties(List<Object> objectList,@NotNull Class<V> clazz,String...ignoreProperties){
        return objectList.stream().map(it -> {
            try {
                return copyProperties(it,clazz,ignoreProperties);
            } catch (InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
    }

    public static <V> @NotNull Page<V> copyProperties(Page<Object> objectPage, @NotNull Class<V> clazz, String...ignoreProperties){
        return new PageImpl<>(
                copyProperties(objectPage.getContent(),clazz,ignoreProperties),
                objectPage.getPageable(),
                objectPage.getTotalElements()
        );
    }
}
